package cmd

import (
	"context"
	"gf-mysql-transfer/internal/controller"
	"gf-mysql-transfer/internal/global"
	"gf-mysql-transfer/internal/metrics"
	"gf-mysql-transfer/internal/middle"
	"gf-mysql-transfer/internal/service"
	"gf-mysql-transfer/internal/storage"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"os"
	"os/signal"
	"syscall"
)

type cStartInput struct {
	g.Meta `name:"start"`
}
type cStartOutput struct{}

func (c cServe) Start(ctx context.Context, in cStartInput) (out *cStartOutput, err error) {
	err = Initialize(ctx)
	if err != nil {
		panic(err)
	}
	if err = startWeb(ctx); err != nil {
		panic(err)
	}
	global.InitializeCluster()
	err = service.Initialize(ctx)
	if err != nil {
		panic(err)
	}

	if err = metrics.Initialize(); err != nil {
		panic(err)
	}
	service.StartUp(ctx) // start application

	s := make(chan os.Signal, 1)
	signal.Notify(s, os.Kill, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	sin := <-s
	glog.Printf(ctx, "application stop，signal: %s \n", sin.String())

	service.Close()
	storage.Close()
	return
}

func startWeb(ctx context.Context) error {
	//web
	if !g.Cfg().MustGetWithEnv(ctx, "server.enabled").Bool() {
		return nil
	}
	s := g.Server()
	s.Use(ghttp.MiddlewareCORS, middle.MiddlewareHandlerResponse)
	s.Group("/", func(group *ghttp.RouterGroup) {
		group.Bind(controller.Index)
	})
	err := s.Start()
	if err == nil {
		config := global.Cfg()
		config.EnableWebAdmin = true
		config.WebAdminPort = s.GetListenedPort()
	}
	return err
}
